package com.heima.article.service.impl;

import com.heima.article.service.ArticleCollectionService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.thread.ApThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Transactional
@Service
public class ArticleCollectionServiceImpl implements ArticleCollectionService {

    @Autowired
    private CacheService cacheService;

    /**
     * 收藏文章
     * 以前缀+用户id为rediskey，前缀+文章id为hashkey，value指定为1,设计哈希表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collectionBehavior(CollectionBehaviorDto dto) {
        if(null==dto.getOperation()
                ||null==dto.getEntryId()
                ||dto.getType()>1
                ||dto.getType()<0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        String redisKey = BehaviorConstants.Collection_Article_Redis_Key_Prefix + ApThreadLocalUtil.getUser().getId();
        String hashKey = BehaviorConstants.Collection_Article_Hash_Key_Prefix + dto.getEntryId();
        if(dto.getType()==0){
            cacheService.hPut(redisKey,hashKey,"1");
        }else{
            cacheService.hDelete(redisKey,hashKey);
        }
        return ResponseResult.okResult(200,"操作成功");
    }
}
